package com.zdsoft.site.mina.utils;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class JaxbUtil {
	/** 
     * JavaBean转换成xml 
     * 默认编码UTF-8,默认需要格式化
     * @param obj 
     * @return  
     */  
    public static String convertToXml(Object obj) {  
        return convertToXml(obj, "UTF-8",true);  
    }  
    /**
     * JavaBean转换成xml 
     * 默认编码UTF-8
     * @param obj 需转换的对象
     * @param format 是否需要格式化
     * @return
     */
    public static String convertToXml(Object obj,boolean format) {  
        return convertToXml(obj, "UTF-8",format);  
    }
    /** 
     * JavaBean转换成xml 
     * @param obj       需要转换的对象 
     * @param encoding  编码
     * @param format    是否格式化
     * @return  
     */  
    public static String convertToXml(Object obj, String encoding,boolean format) {  
        String result = null;  
        try {  
            JAXBContext context = JAXBContext.newInstance(obj.getClass());  
            Marshaller marshaller = context.createMarshaller();  
            //决定是否在转换成xml时同时进行格式化（即按标签自动换行，否则即是一行的xml）
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, format);
            //xml的编码方式
            marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);  
  
            StringWriter writer = new StringWriter();  
            marshaller.marshal(obj, writer);  
            result = writer.toString();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
  
        return result;  
    } 
    /** 
     * xml转换成JavaBean 
     * @param xml 
     * @param c 
     * @return 
     */  
    @SuppressWarnings("unchecked")  
    public static <T> T converyToJavaBean(String xml, Class<T> c) {  
        T t = null;  
        try {  
            JAXBContext context = JAXBContext.newInstance(c);  
            Unmarshaller unmarshaller = context.createUnmarshaller();  
            t = (T) unmarshaller.unmarshal(new StringReader(xml));  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return t;  
    }
}
